package com.sibu.yx.promotion.admin.web.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.doubo.common.model.response.CommonResponse;
import com.doubo.common.util.StringUtil;
import com.sibu.yx.promotion.admin.web.support.model.PhonePasswordToken;
import com.sibu.yx.promotion.common.enums.AliYunSmsTemplateEnum;
import com.sibu.yx.promotion.common.enums.RedisKeyEnum;
import com.sibu.yx.promotion.common.manage.ResponseManage;
import com.sibu.yx.promotion.persistence.model.sys.SysRole;
import com.sibu.yx.promotion.persistence.model.sys.SysUser;
import com.sibu.yx.promotion.persistence.config.AppConfig;
import com.sibu.yx.promotion.service.SmsService;
import com.sibu.yx.promotion.service.sys.SysRoleService;
import com.sibu.yx.promotion.service.sys.SysUserService;

/**
 * @author yuwenbo
 * @create 2019-02-16 14:47
 **/
@RestController
@RequestMapping(value = "/", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class LoginController extends BaseController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SmsService smsService;

    @PostMapping(value = "/login")
    public CommonResponse platformLogin(String userName, String code) {
        CommonResponse<UsernamePasswordToken> commonResponse = checkOnLogin(userName, code);
        if (!commonResponse.isSuccess()) {
            return commonResponse;
        }

        Subject subject = SecurityUtils.getSubject();
        String errorMsg = "";
        try {
            subject.login(commonResponse.getResult());
            if (subject.isAuthenticated()) {
                return ResponseManage.success();
            }
        } catch (IncorrectCredentialsException e) {
            errorMsg = "登录密码错误";
        } catch (ExcessiveAttemptsException e) {
            errorMsg = "登录失败次数过多";
        } catch (LockedAccountException e) {
            errorMsg = "帐号已被锁定";
        } catch (DisabledAccountException e) {
            errorMsg = "帐号已被禁用";
        } catch (ExpiredCredentialsException e) {
            errorMsg = "帐号已过期";
        } catch (UnknownAccountException e) {
            errorMsg = "帐号或密码不正确";
        } catch (UnauthorizedException e) {
            errorMsg = "您没有得到相应的授权！";
        }
        return ResponseManage.fail(errorMsg);
    }

    private CommonResponse<UsernamePasswordToken> checkOnLogin(String userName, String code) {

        if (StringUtil.isBlank(userName)) {
            return ResponseManage.fail("账号不能为空");
        }
        if (StringUtil.isBlank(code)) {
            return ResponseManage.fail("验证码不能为空");
        }
        CommonResponse<SysUser> userRes = sysUserService.selectUser(userName);
        if (!userRes.isSuccess()) {
            return ResponseManage.fail(userRes.getErrorMsg());
        }

        if ("dev".equalsIgnoreCase(AppConfig.getInstance().getEnvironmentName()) && "admin".equals(userName)) {
            if ("123456".equalsIgnoreCase(code)) {
                PhonePasswordToken token = new PhonePasswordToken(userName, code);
                return ResponseManage.success(token);
            }
        }
        SysUser sysUser = userRes.getResult();

        if(!smsService.checkSms(sysUser.getPhone(), code, RedisKeyEnum.REDIS_SMS_TEXT)){
            return ResponseManage.fail("验证码错误");
        }

        PhonePasswordToken token = new PhonePasswordToken(sysUser.getUserName(), code);
        return ResponseManage.success(token);

    }


    @PostMapping(value = "/sendCode")
    public CommonResponse platformSendCode(String userName) {
        CommonResponse<SysUser> userRes = sysUserService.selectUser(userName);
        if (userRes.isSuccess()) {
            SysUser user = userRes.getResult();
            if (user == null) {
                return ResponseManage.fail("用户无效");
            }
            if (user.getPhone() == null || user.getPhone().length() != 11) {
                return ResponseManage.fail("手机号无效");
            }
            SysRole sysRole = sysRoleService.getByName("higoCityRankActivityOperator").getResult();
            if (sysRole != null && !user.getRoleIdsSet().contains(sysRole.getId())) {
                return ResponseManage.fail("您无权限登录，请授权角色【嗨购城市运营活动管理者】");
            }

            CommonResponse<String> resultCommonResponse = smsService.sendSmsVerifyWithParam(user.getPhone(),
                    RedisKeyEnum.REDIS_SMS_TEXT,
                    AliYunSmsTemplateEnum.USER_LOGIN_SMS_CODE_MSG, "思埠嗨购活动后台");
            if (resultCommonResponse.isSuccess()) {
                return ResponseManage.success("验证码发送成功，请注意查收有效期30分钟");
            } else {
                return resultCommonResponse;
            }

        }
        return ResponseManage.fail("用户不存在");
    }
}
